//
//  TestCorTextView1.m
//  BookTest1
//
//  Created by IOS3 on 2018/10/31.
//  Copyright © 2018 IOS3. All rights reserved.
//

#import "TestCorTextView1.h"
#import <CoreText/CoreText.h>

@implementation TestCorTextView1

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:@"hello core text world. 中文字符"];
    CTFontRef font = CTFontCreateWithName(CFSTR("Georgia"), 40, NULL);
    // 斜体
    CTFontRef font2 = CTFontCreateWithName((CFStringRef)[UIFont italicSystemFontOfSize:20].fontName, 40, NULL);
    [attr addAttribute:(id)kCTFontAttributeName value:(__bridge id)font2 range:NSMakeRange(0, 5)];
    
    // 下划线
    [attr addAttribute:(id)kCTUnderlineStyleAttributeName value:(id)[NSNumber numberWithInt:kCTUnderlineStyleDouble] range:NSMakeRange(0, 5)];
    
    // 间隔
    long number = 5;
    CFNumberRef num = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt8Type, &number);
    [attr addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(6, 4)];
    
    //设置字体颜色
    [attr addAttribute:(id)kCTForegroundColorAttributeName value:(id)[UIColor redColor].CGColor range:NSMakeRange(0, 9)];
    
    //设置字体颜色为前影色
    CFBooleanRef flag = kCFBooleanTrue;
    [attr addAttribute:(id)kCTForegroundColorFromContextAttributeName value:(__bridge id)flag range:NSMakeRange(5, 10)];
    
    //设置空心字
    long number2 = 2;
    CFNumberRef num2 = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number2);
    [attr addAttribute:(id)kCTStrokeWidthAttributeName value:(__bridge id)num2 range:NSMakeRange(0, [attr.string length])];
    
    NSRange kk = NSMakeRange(0, 4);
    NSDictionary *dc = [attr attributesAtIndex:0 effectiveRange:&kk];
    [attr endEditing];
    NSLog(@"dc: %@", dc);
    
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, rect);
    // CGPath 做文字绘制的区域

    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attr);
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, [attr length]), path, NULL);
    
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    //压栈，压入图形状态栈中.每个图形上下文维护一个图形状态栈，并不是所有的当前绘画环境的图形状态的元素都被保存。图形状态中不考虑当前路径，所以不保存
    //保存现在得上下文图形状态。不管后续对context上绘制什么都不会影响真正得屏幕。
    CGContextSaveGState(context);
    //x，y轴方向移动
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    //缩放x，y轴方向缩放，－1.0为反向1.0倍,坐标系转换,沿x轴翻转180度
    CGContextScaleCTM(context, 1.0, -1.0);
    
    CTFrameDraw(frame, context);
    // CTFramesetter 管理字体和CFFrameRef
    
    CFRelease(frame);
    CFRelease(path);
    CFRelease(frameSetter);
}

@end
